package com.shchekoldin.juliet.packager.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FilesFinder {

    private static FilesFinder instance = null;

    // -------------------------------------------------------
    // -                      INSTANCE                       -
    // -------------------------------------------------------

    public static FilesFinder getInstance() {
        if (instance == null) instance = new FilesFinder();
        return instance;
    }

    private FilesFinder() { }

    // -------------------------------------------------------
    // -                        LOGIC                        -
    // -------------------------------------------------------

    private List<String> findFilesInDir(String fileDirName, String[] extensions, String basePath, boolean recursive) {
        List<String> result = new ArrayList<String>();
        File dir = new File(basePath + fileDirName);
        File[] filesInDir = dir.listFiles();

        for (File currentFile : filesInDir) {
            if (recursive && currentFile.isDirectory()) {
                result.addAll(findFilesInDir(fileDirName + currentFile.getName() + "/", extensions, basePath,
                    recursive));
                continue;
            }

            for (String extension : extensions) {
                if (currentFile.getName().endsWith(extension)) {
                    result.add(fileDirName + currentFile.getName());
                    break;
                }
            }
        }

        return result;
    }

    //
    // API
    //

    public boolean isRegexpPath(String path) {
        return ((path.indexOf("*") != -1) || (path.indexOf("**") != -1));
    }

    public List<String> findFiles(String regexPath, String basePath) {
        boolean recursive = (regexPath.indexOf("**") != -1);
        String regexSymbol = (recursive ? "**" : "*");
        String extension = regexPath.substring(regexPath.indexOf(regexSymbol) + regexSymbol.length(),
            regexPath.length());
        String fileDirName = regexPath.replace(regexSymbol + extension, "");
        String[] extensions = extension.split("\\|");

        return findFilesInDir(fileDirName, extensions, basePath, recursive);
    }

}
